﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Cherry.Agile.Distributed.Queue.Impl;
using System.ServiceModel.Web;
using System.ServiceModel.Description;
using Cherry.Agile.Distributed.Queue;

namespace Cherry.Agile.Distributed.Queue
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class QueueService : IQueueHandler
    {
        static IQueueRepository repository;
        static QueueService()
        {
            var args = System.Configuration.ConfigurationManager.GetSection("queue") as System.Collections.Specialized.NameValueCollection;
            repository = new RAMQueueRepository(args);
        }

        public string Get(string queueName)
        {
            int index;
            return repository.Get(queueName, null,out index);
        }

        public string Get(string queueName, out int index)
        {
            return repository.Get(queueName, null, out index);
        }

        public string View(string queueName, int index)
        {
            int i;
            return repository.Get(queueName, index,out i);
        }

        public int Set(string queueName, string data)
        {
            return repository.Set(queueName, data);
        }

        public string Config(string queueName, string config)
        {
            throw new NotImplementedException();
        }

        public string Status(string queueName)
        {
            throw new NotImplementedException();
        }

        public static void Start(string[] args)
        {
            try {
                var host = new WebServiceHost(typeof(QueueService));
                ServiceDebugBehavior stp = host.Description.Behaviors.Find<ServiceDebugBehavior>();
                if (stp != null)
                    stp.HttpHelpPageEnabled = false;
                host.Open();

                System.Diagnostics.Trace.TraceInformation("QueueService\t service started");
            } catch (Exception) {
                System.Diagnostics.Trace.TraceInformation("QueueService\t service abort.");
            }
            
        }      
    }
}
